package net.oschina.arvin.dbjava.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Arvin
 * @time 2017/9/28 18:24
 */
public class FileUtils {

    /**
     * 将java代码写到java文件
     *
     * @param folderPath 文件夹
     * @param className  类名
     * @param javaCode   java代码
     * @return 返回java文件路径
     */
    public static String writeToJavaFile(String folderPath, String className, String javaCode) {
        File folder = new File(folderPath);
        ensureFolderExists(folder);
        File javaFile = new File(folder, className + ".java");
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(javaFile), "UTF-8"));
            writer.write(javaCode);
            writer.flush();
            return javaFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void ensureFolderExists(File folder) {
        if (!folder.exists()) {
            folder.mkdirs();
        }
    }

    /**
     * 以文本形式读取
     *
     * @param file 文件
     * @return
     */
    public static List<String> readAsStringList(File file) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            List<String> lines = new ArrayList<String>();
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
            return lines;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
